package com.xhl.core.authentication;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author 徐宏亮
 * @description
 * @date 2019/3/6 21:01
 */
@Getter
@Setter
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService customUserServiceImpl;

    /**
     * 功能描述 获取用户信息，组成成认证的 Authentication
     * @author 徐宏亮
     * @date 2019/3/6 21:03
     * @param authentication
     * @return org.springframework.security.core.Authentication
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        UserDetails user = customUserServiceImpl.loadUserByUsername((String) authenticationToken.getPrincipal());
        if (user == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息！");
        }
        //这里的构造函数 new 出来的是认证过的信息
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user, user.getAuthorities());
        //将未认证信息，copy 到已认证的结果中去
        authenticationResult.setDetails(authenticationToken);
        return authenticationResult;
    }

    /**
     * 功能描述 判断传入的值，是否是 SmsCodeAuthenticationToken 类型的
     * @author 徐宏亮
     * @date 2019/3/6 21:02
     * @param authentication
     * @return boolean
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
